#!/usr/bin/env python
"""
Post-Audit Setup Script
Helps configure the system after code audit cleanup
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path

def check_requirements():
    """Check if all required dependencies are available"""
    print("🔍 Checking requirements...")
    
    required_packages = [
        'redis',
        'python-decouple',
        'django-redis',
        'psycopg2-binary'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.replace('-', '_'))
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print(f"❌ Missing packages: {', '.join(missing_packages)}")
        print("Run: pip install " + " ".join(missing_packages))
        return False
    
    print("✅ All required packages are installed")
    return True

def setup_environment():
    """Set up environment configuration"""
    print("🔧 Setting up environment configuration...")
    
    env_example = Path("devops-backend/.env.example")
    env_file = Path("devops-backend/.env")
    
    if not env_file.exists() and env_example.exists():
        shutil.copy(env_example, env_file)
        print("✅ Created .env file from template")
        print("⚠️  Please edit .env file with your actual configuration")
    else:
        print("ℹ️  .env file already exists")

def check_redis():
    """Check if Redis is running"""
    print("🔍 Checking Redis connection...")
    
    try:
        import redis
        r = redis.Redis(host='localhost', port=6379, db=0)
        r.ping()
        print("✅ Redis is running and accessible")
        return True
    except Exception as e:
        print(f"❌ Redis connection failed: {e}")
        print("Please start Redis server: redis-server")
        return False

def run_migrations():
    """Run Django migrations"""
    print("🔄 Running Django migrations...")
    
    os.chdir("devops-backend")
    
    try:
        subprocess.run([sys.executable, "manage.py", "migrate"], check=True)
        print("✅ Migrations completed successfully")
    except subprocess.CalledProcessError as e:
        print(f"❌ Migration failed: {e}")
        return False
    
    return True

def run_tests():
    """Run Django tests"""
    print("🧪 Running tests...")
    
    try:
        result = subprocess.run([sys.executable, "manage.py", "test"], 
                              capture_output=True, text=True)
        
        if result.returncode == 0:
            print("✅ All tests passed")
            return True
        else:
            print(f"❌ Tests failed:\n{result.stdout}\n{result.stderr}")
            return False
    except Exception as e:
        print(f"❌ Test execution failed: {e}")
        return False

def check_frontend():
    """Check frontend setup"""
    print("🔍 Checking frontend setup...")
    
    os.chdir("../devops-frontend")
    
    if not Path("node_modules").exists():
        print("📦 Installing frontend dependencies...")
        try:
            subprocess.run(["npm", "install"], check=True)
            print("✅ Frontend dependencies installed")
        except subprocess.CalledProcessError as e:
            print(f"❌ Frontend installation failed: {e}")
            return False
    else:
        print("✅ Frontend dependencies already installed")
    
    return True

def generate_report():
    """Generate setup report"""
    print("\n" + "="*50)
    print("📋 POST-AUDIT SETUP REPORT")
    print("="*50)
    
    checks = [
        ("Python Dependencies", check_requirements()),
        ("Environment Config", True),  # Always true after setup
        ("Redis Connection", check_redis()),
        ("Database Migrations", run_migrations()),
        ("Test Suite", run_tests()),
        ("Frontend Setup", check_frontend())
    ]
    
    print("\n🔍 Setup Status:")
    for check_name, status in checks:
        status_icon = "✅" if status else "❌"
        print(f"  {status_icon} {check_name}")
    
    all_passed = all(status for _, status in checks)
    
    if all_passed:
        print("\n🎉 All setup checks passed!")
        print("\n📝 Next steps:")
        print("  1. Review and update .env file with your settings")
        print("  2. Start Redis server if not running")
        print("  3. Run: python manage.py runserver (backend)")
        print("  4. Run: npm run dev (frontend)")
    else:
        print("\n⚠️  Some setup checks failed. Please resolve the issues above.")
    
    return all_passed

def main():
    """Main setup function"""
    print("🚀 DevOps Platform Post-Audit Setup")
    print("This script helps configure your system after the code audit cleanup.\n")
    
    # Change to project root
    script_dir = Path(__file__).parent
    project_root = script_dir.parent
    os.chdir(project_root)
    
    setup_environment()
    success = generate_report()
    
    if success:
        print("\n✅ Setup completed successfully!")
    else:
        print("\n❌ Setup completed with issues. Please check the report above.")
    
    return 0 if success else 1

if __name__ == "__main__":
    sys.exit(main())
